package TheadConsumerAndProducerTest;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author chenjunjie
 * @since 2018-02-11
 */
public class ConsumerAndProducer {
    private int value;
    private ReentrantLock lock;
    private Condition condition;
    public ConsumerAndProducer(ReentrantLock lock){
        this.lock = lock;
        this.condition = lock.newCondition();
    }

    public void consume(){
        lock.lock();
        while(value <= 0){
            try {
                condition.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.printf("start consume...  getHoldCount=%d\t",lock.getHoldCount());
        value--;
        System.out.printf("value=%d \n",value);
        condition.signalAll();
        lock.unlock();
    }


    public void produce(){
        lock.lock();
        while(value >= 20){
            try {
                condition.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.printf("start produce...  getHoldCount=%d\t  ",lock.getHoldCount());
        value++;
        System.out.printf("value=%d \n",value);
        condition.signalAll();
        lock.unlock();
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }
}
